Popular Searches
Popular Course Categories
Popular Courses

Introduction to Dictionaries and Key-Value Pairs

Introduction to Dictionaries and Key-Value Pairs

Python Dictionaries, Sets, and Comprehensions

Introduction to Dictionaries and Key-Value Pairs in Python

Course: Python Training

Topic: Introduction to Dictionaries and Key-Value Pairs

Course Link: Python Training Course

Demo Registration: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Dictionaries

A dictionary is a built-in Python data structure that stores information as key-value pairs. Each key is associated with a value, allowing programmers to organize and retrieve information using meaningful identifiers instead of numeric positions.

For example, a student record can store a student's name, age, course, and marks in a single dictionary. Instead of remembering which list index contains the student's name, you can retrieve it directly using the key "name".

student = {
    "name": "Amit",
    "age": 21,
    "course": "Python",
    "marks": 88
}

print(student)

Output:

{'name': 'Amit', 'age': 21, 'course': 'Python', 'marks': 88}

Dictionaries are especially useful for storing user profiles, product details, employee records, configuration settings, API responses, and other structured information.

2. Learning Objectives

  • Understand dictionaries and key-value pairs.
  • Learn the syntax for creating dictionaries.
  • Understand the rules for dictionary keys and values.
  • Access dictionary values using keys.
  • Add, update, and remove key-value pairs.
  • Check whether keys exist in a dictionary.
  • Use common dictionary methods.
  • Iterate through dictionary keys, values, and items.
  • Understand nested dictionaries and practical applications.

3. What Is a Key-Value Pair?

A key-value pair is a combination of two parts: a key that identifies an entry and a value that stores the associated information. A colon (:) separates the key from its value.

employee = {
    "name": "Priya",
    "department": "IT",
    "salary": 45000
}
Key Value Meaning
"name" "Priya" Employee's name
"department" "IT" Employee's department
"salary" 45000 Employee's salary

In this example, "department" is the key and "IT" is its associated value.

3.1 Why Are Key-Value Pairs Useful?

  • They make data easier to understand and organize.
  • They allow values to be retrieved using meaningful keys.
  • They help group related information into one structure.
  • They support efficient lookup for many common applications.
  • They are commonly used when working with JSON data, APIs, and configuration files.

4. Characteristics of Python Dictionaries

Characteristic Explanation
Key-value structure Each dictionary entry associates a key with a value.
Mutable Entries can be added, updated, and removed.
Unique keys Each key can appear only once in a dictionary.
Insertion order Python dictionaries preserve the order in which keys are inserted.
Flexible values Values can be strings, numbers, lists, dictionaries, Boolean values, or other objects.
Hashable keys Keys must be hashable, such as strings, integers, or suitable tuples.
No numeric positional indexing Dictionary entries are accessed by keys, not by list-style numeric positions.

Although dictionaries preserve insertion order, their primary purpose is mapping keys to values rather than representing a sequence of items.


5. Creating Dictionaries in Python

5.1 Creating a Dictionary Using Curly Braces

The most common way to create a dictionary is by placing comma-separated key-value pairs inside curly braces {}.

student = {
    "name": "Rohan",
    "age": 22,
    "city": "Mumbai"
}

print(student)

Output:

{'name': 'Rohan', 'age': 22, 'city': 'Mumbai'}

5.2 Creating an Empty Dictionary

An empty dictionary contains no key-value pairs. You can add entries later.

student = {}

student["name"] = "Neha"
student["age"] = 20

print(student)

Output:

{'name': 'Neha', 'age': 20}

Important: Use {} to create an empty dictionary. The expression set() creates an empty set, not a dictionary.

5.3 Creating a Dictionary with dict()

The built-in dict() constructor provides another way to create a dictionary.

student = dict(name="Amit", age=21, course="Python")

print(student)

Output:

{'name': 'Amit', 'age': 21, 'course': 'Python'}

When using keyword arguments with dict(), the argument names become string keys. For keys containing spaces or special characters, use curly-brace syntax or an iterable of key-value pairs.

5.4 Creating a Dictionary from Key-Value Pairs

pairs = [
    ("name", "Priya"),
    ("age", 23),
    ("course", "Data Analytics")
]

student = dict(pairs)

print(student)

Output:

{'name': 'Priya', 'age': 23, 'course': 'Data Analytics'}

6. Understanding Dictionary Keys and Values

6.1 Rules for Dictionary Keys

  • Keys must be unique within the dictionary.
  • Keys must be hashable.
  • Strings, integers, and many other immutable values can be used as keys.
  • Tuples can be keys if all their contents are hashable.
  • Lists and dictionaries cannot be used as dictionary keys because they are mutable and unhashable.
data = {
    "name": "Asha",
    101: "Employee ID",
    (1, 2): "Coordinate"
}

print(data["name"])
print(data[101])
print(data[(1, 2)])

Output:

Asha
Employee ID
Coordinate

Using a list as a key raises a TypeError:

# Invalid example
data = {[1, 2]: "Example"}

6.2 Values Can Be Different Data Types

Dictionary values can contain different types of information, including other collections.

product = {
    "name": "Laptop",
    "price": 55000,
    "available": True,
    "colors": ["Black", "Silver"],
    "discount": None
}

print(product["name"])
print(product["colors"])
print(product["available"])

Output:

Laptop
['Black', 'Silver']
True

6.3 Duplicate Keys

If the same key is specified multiple times in a dictionary literal, the later value replaces the earlier value.

student = {
    "name": "Amit",
    "age": 20,
    "age": 22
}

print(student)

Output:

{'name': 'Amit', 'age': 22}

Because keys are unique, the dictionary contains only one "age" entry.


7. Accessing Dictionary Values

7.1 Accessing Values with Square Brackets

Use the key inside square brackets to retrieve its associated value.

employee = {
    "name": "Priya",
    "department": "IT",
    "salary": 45000
}

print(employee["name"])
print(employee["salary"])

Output:

Priya
45000

If the requested key does not exist, square-bracket access raises a KeyError.

7.2 Accessing Values with get()

The get() method retrieves a value without raising a KeyError when the key is missing. By default, it returns None for a missing key, or you can supply a default value.

employee = {
    "name": "Priya",
    "department": "IT"
}

print(employee.get("name"))
print(employee.get("salary"))
print(employee.get("salary", 0))

Output:

Priya
None
0

7.3 Square Brackets vs. get()

Operation Behavior when key exists Behavior when key is missing
data[key] Returns the associated value. Raises KeyError.
data.get(key) Returns the associated value. Returns None by default.
data.get(key, default) Returns the associated value. Returns the supplied default.

8. Adding and Updating Dictionary Entries

8.1 Adding a New Key-Value Pair

Assign a value to a new key to add an entry.

student = {
    "name": "Rohan",
    "age": 21
}

student["course"] = "Python"

print(student)

Output:

{'name': 'Rohan', 'age': 21, 'course': 'Python'}

8.2 Updating an Existing Value

Assigning a value to a key that already exists replaces the previous value associated with that key.

student = {
    "name": "Rohan",
    "age": 21
}

student["age"] = 22

print(student)

Output:

{'name': 'Rohan', 'age': 22}

8.3 Updating Multiple Entries with update()

The update() method adds new entries and replaces values for keys that already exist.

student = {
    "name": "Rohan",
    "age": 21
}

student.update({
    "age": 22,
    "course": "Python",
    "city": "Mumbai"
})

print(student)

Output:

{'name': 'Rohan', 'age': 22, 'course': 'Python', 'city': 'Mumbai'}

9. Removing Dictionary Entries

9.1 The pop() Method

The pop() method removes the specified key and returns its associated value.

student = {
    "name": "Amit",
    "age": 21,
    "course": "Python"
}

removed_course = student.pop("course")

print(removed_course)
print(student)

Output:

Python
{'name': 'Amit', 'age': 21}

If the key is absent, pop() raises a KeyError unless a default value is provided.

9.2 The popitem() Method

The popitem() method removes and returns the last inserted key-value pair as a tuple.

product = {
    "name": "Keyboard",
    "price": 1500,
    "stock": 20
}

removed_item = product.popitem()

print(removed_item)
print(product)

Output:

('stock', 20)
{'name': 'Keyboard', 'price': 1500}

9.3 The del Statement

The del statement removes a specific key-value pair.

student = {
    "name": "Priya",
    "age": 22,
    "city": "Pune"
}

del student["city"]

print(student)

Output:

{'name': 'Priya', 'age': 22}

9.4 The clear() Method

The clear() method removes all entries from a dictionary.

settings = {
    "theme": "dark",
    "language": "English"
}

settings.clear()

print(settings)

Output:

{}

10. Checking Whether a Key Exists

Use the in operator to check whether a key exists in a dictionary. Use not in to check whether it does not exist.

student = {
    "name": "Asha",
    "age": 20,
    "course": "Python"
}

print("name" in student)
print("salary" in student)
print("salary" not in student)

Output:

True
False
True

For dictionaries, the in operator checks keys, not values.

student = {"name": "Asha", "course": "Python"}

print("name" in student)
print("Asha" in student)
print("Asha" in student.values())

Output:

True
False
True

11. Important Dictionary Methods

11.1 keys()

The keys() method returns a view containing the dictionary's keys.

student = {"name": "Amit", "age": 21, "course": "Python"}

print(student.keys())

Output:

dict_keys(['name', 'age', 'course'])

11.2 values()

The values() method returns a view containing the dictionary's values.

student = {"name": "Amit", "age": 21, "course": "Python"}

print(student.values())

Output:

dict_values(['Amit', 21, 'Python'])

11.3 items()

The items() method returns a view of the dictionary's key-value pairs. Each pair is represented as a tuple.

student = {"name": "Amit", "age": 21}

print(student.items())

Output:

dict_items([('name', 'Amit'), ('age', 21)])

11.4 copy()

The copy() method creates a shallow copy of a dictionary.

original = {"name": "Amit", "age": 21}
copied = original.copy()

copied["age"] = 22

print(original)
print(copied)

Output:

{'name': 'Amit', 'age': 21}
{'name': 'Amit', 'age': 22}

A shallow copy creates a new outer dictionary, but nested mutable values may still be shared between the two dictionaries.

11.5 setdefault()

The setdefault() method returns the value for a key if it exists. If the key does not exist, it inserts the key with the specified default value and returns that value.

employee = {"name": "Priya"}

result = employee.setdefault("department", "IT")

print(result)
print(employee)

Output:

IT
{'name': 'Priya', 'department': 'IT'}

11.6 Dictionary Method Summary

Method Purpose
get(key, default) Returns a value or a default when the key is missing.
update(other) Adds or updates entries.
pop(key) Removes a key and returns its value.
popitem() Removes and returns the last inserted key-value pair.
clear() Removes all entries.
keys() Returns a view of keys.
values() Returns a view of values.
items() Returns a view of key-value pairs.
copy() Creates a shallow copy.
setdefault(key, default) Returns an existing value or inserts a default value.

12. Iterating Through Dictionaries

12.1 Iterating Through Keys

Using a dictionary directly in a for loop iterates over its keys.

student = {
    "name": "Amit",
    "age": 21,
    "course": "Python"
}

for key in student:
    print(key)

Output:

name
age
course

12.2 Iterating Through Values

student = {
    "name": "Amit",
    "age": 21,
    "course": "Python"
}

for value in student.values():
    print(value)

Output:

Amit
21
Python

12.3 Iterating Through Key-Value Pairs

Use items() to access both keys and values in a loop.

student = {
    "name": "Amit",
    "age": 21,
    "course": "Python"
}

for key, value in student.items():
    print(key, ":", value)

Output:

name : Amit
age : 21
course : Python

13. Nested Dictionaries

A nested dictionary is a dictionary that contains another dictionary as a value. This structure is useful when a record contains multiple related groups of information.

students = {
    "student1": {
        "name": "Amit",
        "marks": 85
    },
    "student2": {
        "name": "Priya",
        "marks": 92
    }
}

print(students)

13.1 Accessing Nested Dictionary Values

Use successive keys to access values at different levels.

print(students["student1"]["name"])
print(students["student2"]["marks"])

Output:

Amit
92

13.2 Updating Nested Dictionary Values

students["student1"]["marks"] = 90

print(students["student1"])

Output:

{'name': 'Amit', 'marks': 90}

13.3 Adding a New Nested Record

students["student3"] = {
    "name": "Rahul",
    "marks": 81
}

print(students["student3"])

Output:

{'name': 'Rahul', 'marks': 81}

14. Dictionary Comprehensions

A dictionary comprehension creates a dictionary using a compact expression. It can be used to transform values or generate key-value pairs from an iterable.

14.1 Creating a Dictionary of Squares

squares = {number: number ** 2 for number in range(1, 6)}

print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

14.2 Filtering Entries with a Condition

numbers = [1, 2, 3, 4, 5, 6]

squares = {
    number: number ** 2
    for number in numbers
    if number % 2 == 0
}

print(squares)

Output:

{2: 4, 4: 16, 6: 36}

15. Practical Example: Student Record Manager

The following program demonstrates how dictionaries can store student information and support adding, updating, accessing, and displaying records.

students = {
    101: {"name": "Amit", "marks": 85},
    102: {"name": "Priya", "marks": 92},
    103: {"name": "Rahul", "marks": 78}
}

# Add a new student
students[104] = {"name": "Neha", "marks": 88}

# Update an existing student's marks
students[103]["marks"] = 82

# Retrieve a student's details
print("Student 102:", students.get(102))

# Display all student records
for student_id, details in students.items():
    print(student_id, details["name"], details["marks"])

Output:

Student 102: {'name': 'Priya', 'marks': 92}
101 Amit 85
102 Priya 92
103 Rahul 82
104 Neha 88

This example demonstrates the usefulness of dictionaries for storing structured records. A unique student ID acts as the key, while a nested dictionary stores the student's details.

16. Common Mistakes and Troubleshooting

Mistake Explanation Solution
Using a missing key with square brackets Python raises a KeyError. Use get() or check whether the key exists.
Using duplicate keys The later value replaces the earlier value. Use unique keys when each entry must be preserved separately.
Using a list as a key Lists are unhashable. Use a suitable immutable key, such as a string or tuple of hashable values.
Confusing keys and values The in operator checks keys by default. Use value in dictionary.values() to check values.
Assuming copy() duplicates nested objects copy() creates a shallow copy. Use copy.deepcopy() when an independent recursive copy is required.
Removing a missing key pop() and del can raise KeyError. Check the key or use pop(key, default).
Confusing an empty dictionary with an empty set {} creates a dictionary. Use set() to create an empty set.

17. Best Practices for Dictionaries

  • Use descriptive keys such as "email", "price", and "student_id".
  • Choose consistent key naming conventions throughout a project.
  • Use get() when a key may be absent and a default value is appropriate.
  • Use items() when both keys and values are required in a loop.
  • Use nested dictionaries when records contain multiple related fields.
  • Avoid using mutable objects as dictionary keys.
  • Do not assume that duplicate keys will preserve multiple values; a dictionary stores only one value per key.
  • Use copy.deepcopy() when you need to copy nested mutable structures independently.
  • Validate external data before relying on required keys or expected value types.

18. Practice Exercises

Exercise 1: Create a Dictionary

Create a dictionary containing a person's name, age, and city. Print each value separately.

person = {
    "name": "Meera",
    "age": 24,
    "city": "Mumbai"
}

print(person["name"])
print(person["age"])
print(person["city"])

Expected output:

Meera
24
Mumbai

Exercise 2: Add and Update Values

Create a product dictionary. Add a stock value and update the price.

product = {
    "name": "Mouse",
    "price": 800
}

product["stock"] = 25
product["price"] = 750

print(product)

Expected output:

{'name': 'Mouse', 'price': 750, 'stock': 25}

Exercise 3: Use Dictionary Methods

Print all keys, all values, and all key-value pairs from a dictionary.

course = {
    "name": "Python",
    "duration": "3 months",
    "level": "Beginner"
}

print(list(course.keys()))
print(list(course.values()))
print(list(course.items()))

Expected output:

['name', 'duration', 'level']
['Python', '3 months', 'Beginner']
[('name', 'Python'), ('duration', '3 months'), ('level', 'Beginner')]

Exercise 4: Create a Nested Dictionary

Create a dictionary containing two employees and their department and salary. Display the second employee's salary.

employees = {
    "E101": {"name": "Asha", "department": "HR", "salary": 35000},
    "E102": {"name": "Vikram", "department": "IT", "salary": 50000}
}

print(employees["E102"]["salary"])

Expected output:

50000

Exercise 5: Count Word Frequencies

Use a dictionary to count how many times each word appears in a list.

words = ["python", "java", "python", "sql", "java", "python"]
frequency = {}

for word in words:
    frequency[word] = frequency.get(word, 0) + 1

print(frequency)

Expected output:

{'python': 3, 'java': 2, 'sql': 1}

19. Interview Questions and Answers

Q1. What is a dictionary in Python?

A dictionary is a mutable data structure that stores key-value pairs and retrieves values using their associated keys.

Q2. How do you create an empty dictionary?

Use {} or dict().

Q3. Can dictionary keys be duplicated?

No. Keys are unique within a dictionary. If the same key appears more than once in a dictionary literal, the later value replaces the earlier value.

Q4. Can a list be used as a dictionary key?

No. Lists are mutable and unhashable, so they cannot be used as dictionary keys.

Q5. What is the difference between get() and square-bracket access?

Square-bracket access raises a KeyError for a missing key. The get() method returns None or a specified default value when the key is missing.

Q6. What does the update() method do?

It adds new key-value pairs and updates values for keys that already exist.

Q7. What is the difference between keys(), values(), and items()?

keys() returns a view of keys, values() returns a view of values, and items() returns a view of key-value pairs.

Q8. What is a nested dictionary?

A nested dictionary is a dictionary that contains other dictionaries as values. It is useful for representing structured records.

Q9. How can you check whether a key exists?

Use the in operator, such as "name" in student.

Q10. What is the difference between pop() and popitem()?

pop(key) removes a specified key and returns its value. popitem() removes and returns the last inserted key-value pair.

Q11. Does a dictionary preserve insertion order?

Yes. Modern Python dictionaries preserve insertion order as a language guarantee.

Q12. What is a dictionary comprehension?

A dictionary comprehension is a compact way to create a dictionary from an iterable using expressions and optional conditions.


20. Quick Revision Checklist

  • A dictionary stores data as key-value pairs.
  • Dictionaries are created using curly braces or the dict() constructor.
  • Keys must be unique and hashable.
  • Values can contain different data types, including lists and dictionaries.
  • Use dictionary[key] to access a value when the key is expected to exist.
  • Use get() to handle potentially missing keys.
  • Use assignment or update() to add and modify entries.
  • Use pop(), popitem(), del, or clear() to remove entries.
  • Use keys(), values(), and items() to inspect dictionary contents.
  • Use nested dictionaries to organize related records.
  • Use dictionary comprehensions for concise dictionary creation.

21. Conclusion

Dictionaries are essential in Python because they provide an organized way to store and retrieve information through key-value pairs. Their flexibility makes them useful for records, settings, structured datasets, and application data.

By understanding dictionary creation, key rules, value access, updates, deletion, iteration, and nested structures, you can build more organized and maintainable Python programs. Practice the examples and exercises in this lesson to strengthen your understanding before moving on to more advanced dictionary operations.

Additional Learning Resources

whatsapp